<template>
  <el-cascader
    v-model="categoryIdList"
    :options="categoryOptions"
    @change="handleChange"
    :placeholder="placeholder"
    :props="{ checkStrictly: true, expandTrigger: 'hover' }"
    style="width: 100%"
    clearable
    filterable/>
</template>

<script setup>
import { onMounted, ref, watch, nextTick } from "vue";
import { useProduct } from "@/pinia/modules/product";
import CategoryApi from "@/api/product/category";

const productStore = useProduct();

const props = defineProps({
  searchCategoryIdList: {
    type: Array
  },
  placeholder: {
    type: String,
    default: '请选择分类'
  }
})

const categoryIdList = ref([])
watch(() => props.searchCategoryIdList, newValue => {
  nextTick(() => {
    // 数据回显，过滤子节点为0的数据
    categoryIdList.value = newValue.filter(item => item !== 0)
    // handleChange(categoryIdList.value)
  })
})

// 自定义事件
const emits = defineEmits(['handleChange'])
// 分类数据
const categoryOptions = ref([]);
// 分类数据处理
const categoryHandle = categories => {
  if (!(categories instanceof Array)) categories = JSON.parse(categories)
  categoryOptions.value = categoryBuildData(categoryBuildByStatus(categories));
}
// 递归构建分类选择控件数据
const categoryBuildData = categories => categories.map(item => {
  if (item.status === 0) return
  return {
    value: item.id,
    label: item.name,
    children: item.children.length ? categoryBuildData(item.children) : []
  }
})
// 递归过滤禁用的分类
const categoryBuildByStatus = categories => categories.filter(item => {
  if (item.children && item.children.length > 0) {
    item.children = categoryBuildByStatus(item.children)
  }
  return item.status === 1
})

// 分类列表
const getCategoryOptions = () => {
  // 从缓存里面拿数据，没有再查数据库
  const categories = productStore.getCategories();
  if (categories != null && categories.length > 0) {
    categoryHandle(categories);
  }
  // 本地缓存没有，请求后端
  else {
    getCategory();
  }
};

// 从数据库获取分类数据
const getCategory = async () => {
  const { data: result } = await CategoryApi.findAll();
  productStore.saveCategories(result);
  categoryHandle(result);
};

// 选择分类
const handleChange = selectedIds => {
  // 获取最后一个选中的分类ID --> selectedIds.at(-1)
  emits('handleChange', selectedIds && selectedIds.at(-1), categoryIdList.value);
}

onMounted(() => {
  getCategoryOptions()
})

</script>
